{% extends "admin/change_list.html" %}
{% load i18n admin_urls static admin_modify %}

{% block object-tools-items %}
    <li>
        <a href="#" class="addlink" onclick="document.getElementById('add-repo-form').style.display='block'; return false;">
            {% blocktranslate with cl.opts.verbose_name as name %}Add {{ name }}{% endblocktranslate %}
        </a>
    </li>
{% endblock %}

{% block content %}
    <div id="add-repo-form" style="margin-bottom: 20px; padding: 20px; background: #f5f5f5; border: 1px solid #ddd; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
        <h2 style="margin-top: 0; margin-bottom: 20px; color: #333; font-size: 1.2em;">添加新仓库</h2>
        <form method="post" action="">
            {% csrf_token %}
            <div class="form-row" style="display: flex; gap: 20px; margin-bottom: 20px;">
                <div style="flex: 2;">
                    {{ add_form.url.label_tag }}
                    {{ add_form.url }}
                    {% if add_form.url.errors %}
                        <div class="error">{{ add_form.url.errors }}</div>
                    {% endif %}
                </div>
                <div style="flex: 1;">
                    {{ add_form.name.label_tag }}
                    {{ add_form.name }}
                    {% if add_form.name.errors %}
                        <div class="error">{{ add_form.name.errors }}</div>
                    {% endif %}
                </div>
            </div>
            <div class="submit-row" style="margin-top: 20px;">
                <input type="submit" value="添加仓库" class="default" name="_save" style="background: #79aec8; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer;">
                <input type="button" value="取消" onclick="document.getElementById('add-repo-form').style.display='none';" style="background: #f5f5f5; border: 1px solid #ddd; padding: 8px 15px; border-radius: 4px; cursor: pointer;">
            </div>
        </form>
    </div>

    {{ block.super }}
{% endblock %}

{% block extrahead %}
    {{ block.super }}
    <script type="text/javascript" src="{% static 'admin/js/repository_form.js' %}"></script>
    <style>
        /* 隐藏搜索框和过滤器 */
        #changelist-search, #changelist-filter {
            display: none !important;
        }

        /* 美化表格 */
        #result_list {
            border: 1px solid #ddd;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        #result_list thead th {
            background: #f5f5f5;
            border-bottom: 2px solid #ddd;
            padding: 10px;
            font-weight: bold;
        }

        #result_list tbody td {
            padding: 10px;
            border-bottom: 1px solid #eee;
        }

        #result_list tbody tr:hover {
            background: #f9f9f9;
        }

        /* 美化状态显示 */
        .field-get_sync_status {
            font-weight: bold;
        }
        .field-get_sync_status.synced {
            color: #28a745;
        }
        .field-get_sync_status.not_synced {
            color: #dc3545;
        }
        .field-get_sync_status.syncing {
            color: #ffc107;
        }

        /* 美化操作按钮 */
        .action-buttons {
            display: flex;
            gap: 8px;
        }
        .action-buttons .button {
            margin-right: 5px;
            background: #79aec8;
            color: white;
            border: none;
            padding: 4px 8px;
            border-radius: 4px;
            text-decoration: none;
            font-size: 0.9em;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .action-buttons .button:hover {
            background: #609ab6;
        }
        .action-buttons .button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .delete-button {
            background: #dc3545 !important;
        }
        .delete-button:hover {
            background: #c82333 !important;
        }

        /* 同步状态指示器 */
        .sync-indicator {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 8px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 同步中的行样式 */
        .syncing-row {
            background-color: #fff3cd !important;
            border-left: 4px solid #ffc107;
        }

        /* 美化添加表单 */
        #add-repo-form {
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        #add-repo-form h2 {
            margin-top: 0;
            margin-bottom: 20px;
            color: #333;
            font-size: 1.2em;
        }
        .submit-row {
            margin-top: 20px;
        }
        .submit-row input {
            margin-right: 10px;
        }

        /* 美化表单字段 */
        .form-row {
            margin-bottom: 15px;
        }
        .form-row label {
            display: block;
            margin-bottom: 5px;
            color: #666;
        }
        .form-row input[type="text"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .form-row input[type="text"]:focus {
            border-color: #79aec8;
            outline: none;
        }

        /* 错误信息样式 */
        .error {
            color: #dc3545;
            font-size: 0.9em;
            margin-top: 5px;
        }
    </style>

    <script>
        // 处理同步操作
        function handleSyncOperation(operation, repoId, button) {
            // 禁用按钮
            button.disabled = true;
            button.style.cursor = 'not-allowed';

            // 获取当前行
            const row = button.closest('tr');
            const statusCell = row.querySelector('.field-get_sync_status');
            const actionButtons = row.querySelector('.action-buttons');

            // 添加同步状态样式
            row.classList.add('syncing-row');

            // 更新状态显示
            if (statusCell) {
                statusCell.innerHTML = '<span class="sync-indicator"></span>正在同步...';
                statusCell.className = 'field-get_sync_status syncing';
            }

            // 隐藏操作按钮
            if (actionButtons) {
                actionButtons.style.display = 'none';
            }

            // 构建URL
            const url = `/admin/grading/repository/${repoId}/${operation}/`;

            // 发送请求
            fetch(url, {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                },
            })
            .then(response => {
                if (response.ok) {
                    // 操作成功，刷新页面
                    window.location.reload();
                } else {
                    throw new Error('操作失败');
                }
            })
            .catch(error => {
                console.error('操作失败:', error);
                // 恢复按钮状态
                button.disabled = false;
                button.style.cursor = 'pointer';

                // 移除同步状态样式
                row.classList.remove('syncing-row');

                // 恢复状态显示
                if (statusCell) {
                    statusCell.innerHTML = '<span style="color: #999;">同步失败</span>';
                    statusCell.className = 'field-get_sync_status not_synced';
                }

                // 显示操作按钮
                if (actionButtons) {
                    actionButtons.style.display = 'flex';
                }

                // 显示错误消息
                alert('操作失败，请重试');
            });
        }

        // 页面加载完成后绑定事件
        document.addEventListener('DOMContentLoaded', function() {
            // 为所有同步按钮添加点击事件
            const syncButtons = document.querySelectorAll('a[href*="/sync/"]');
            syncButtons.forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();

                    // 从URL中提取仓库ID
                    const url = this.getAttribute('href');
                    const match = url.match(/\/(\d+)\/sync\//);
                    if (match) {
                        const repoId = match[1];
                        handleSyncOperation('sync', repoId, this);
                    }
                });
            });

            // 为所有克隆按钮添加点击事件
            const cloneButtons = document.querySelectorAll('a[href*="/clone/"]');
            cloneButtons.forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();

                    // 从URL中提取仓库ID
                    const url = this.getAttribute('href');
                    const match = url.match(/\/(\d+)\/clone\//);
                    if (match) {
                        const repoId = match[1];
                        handleSyncOperation('clone', repoId, this);
                    }
                });
            });
        });
    </script>
{% endblock %}
